package com.oro.backingbeans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.faces.model.SelectItem;
import javax.persistence.Transient;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;

import com.oro.domain.Contatto;
import com.oro.domain.Email;
import com.oro.domain.Fax;
import com.oro.domain.IndirizzoAU;
import com.oro.domain.IndirizzoIT;
import com.oro.domain.Studente;
import com.oro.domain.Telephone;
import com.oro.domain.User;
import com.oro.service.StudentService;

public class InserisciStudenteBean implements ActionListener, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1150134429615026299L;

	private Email emailToRemove;

	private List<SelectItem> emailTypeOptions;
	private Fax faxToRemove;
	@Transient
	private Logger logger;
	private List<SelectItem> phoneCountryOptions;
	private List<SelectItem> phoneTypeOptions;
	private List<SelectItem> stateOptions;
	private Studente studentInput;
	private Studente studentOutput;
	@Autowired
	private StudentService studentService;

	private Telephone telephoneToRemove;

	private int test;

	private List<SelectItem> titleOptions;

	public InserisciStudenteBean() {
		super();
	}

	public void addEmergencyContact() {
		studentInput.add(new Contatto());
	}

	public boolean addEmptyEmail() {
		studentInput.add(new Email());
		return true;
	}

	public boolean addEmptyFax() {
		studentInput.add(new Fax());
		return true;
	}

	public void addEmptyIndAu() {
		studentInput.getIndirizziAu().add(new IndirizzoAU());
	}

	public void addEmptyIndIt() {
		studentInput.getIndirizziIt().add(new IndirizzoIT());
	}

	public boolean addEmptyPhone() {
		studentInput.add(new Telephone());
		return true;
	}

	public Email getEmailToRemove() {
		return emailToRemove;
	}

	public List<SelectItem> getEmailTypeOptions() {
		return emailTypeOptions;
	}

	public Fax getFaxToRemove() {
		return faxToRemove;
	}

	private Object getLoggedUser() {
		Object loggedUser = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		getLogger().info(loggedUser.toString());
		getLogger().info(loggedUser.getClass());
		return loggedUser;
	}

	private Logger getLogger() {
		if (logger == null) {
			logger = Logger.getLogger(InserisciUtenteBean.class);
		}
		return logger;
	}

	public List<SelectItem> getPhoneCountryOptions() {
		return phoneCountryOptions;
	}

	public List<SelectItem> getPhoneTypeOptions() {
		return phoneTypeOptions;
	}

	public List<SelectItem> getStateOptions() {
		return stateOptions;
	}

	public Studente getStudentInput() {
		return studentInput;
	}

	public Studente getStudentOutput() {
		return studentOutput;
	}

	public StudentService getStudentService() {
		return studentService;
	}

	public Telephone getTelephoneToRemove() {
		return telephoneToRemove;
	}

	public int getTest() {
		return test;
	}

	public void plus() {
		test++;
	}

	@PostConstruct
	public void postConstruct() {
		studentInput = new Studente();
		studentOutput = new Studente();
		titleOptions = new ArrayList<SelectItem>();
		for (String title : Contatto.getTitles()) {
			titleOptions.add(new SelectItem(title, title));
		}
		emailTypeOptions = new ArrayList<SelectItem>();
		for (String type : Email.getTypes()) {
			emailTypeOptions.add(new SelectItem(type, type));
		}
		phoneTypeOptions = new ArrayList<SelectItem>();
		for (String type : Telephone.getTypes()) {
			phoneTypeOptions.add(new SelectItem(type, type));
		}
		phoneCountryOptions = new ArrayList<SelectItem>();
		for (String country : Telephone.getCountries()) {
			phoneCountryOptions.add(new SelectItem(country, country));
		}
		stateOptions = new ArrayList<SelectItem>();
		for (String state : IndirizzoAU.getAustralianStates()) {
			stateOptions.add(new SelectItem(state, state));
		}
		getLogger().info("InserisciStudentBean has been constructed.");
	}

	@PreDestroy
	public void preDestroy() {
		getLogger().info("InserisciStudentBean is being destroyed.");
	}

	@Override
	public void processAction(ActionEvent e) throws AbortProcessingException {
		System.out.println("EVENT");
		System.out.println(e.getComponent().getId());
		if (e.getComponent().getId().equals("deleteEmail")) {
			System.out.println("THISISIT");
			if (emailToRemove == null)
				System.out.println("NULL");
			studentInput.remove(emailToRemove);
		}

	}

	public boolean removeEmail() {
		return studentInput.remove(emailToRemove);
	}

	private void removeEmptyEmails() {
		Email e;
		for (Iterator<Email> it = studentInput.getEmails().iterator(); it
				.hasNext();) {
			e = it.next();
			if (e.getEmail() == null || e.getEmail() == "") {
				it.remove();
			}
		}

		// Email[] emails = (Email[]) studentInput.getEmails().toArray(
		// new Email[studentInput.getEmails().size()]);
		// List<Email> newlist = new ArrayList<Email>();
		// for (int i = 0; i < emails.length; i++)
		// if (emails[i].getEmail() != null && emails[i].getEmail() != "")
		// newlist.add(emails[i]);
		// studentInput.setEmails(newlist);
	}

	private void removeEmptyFaxes() {
		Fax e;
		for (Iterator<Fax> it = studentInput.getFaxes().iterator(); it
				.hasNext();) {
			e = it.next();
			if (e.getNumber() == null || e.getNumber() == "") {
				it.remove();
			}
		}

	}

	private void removeEmptyTelephones() {
		Telephone e;
		for (Iterator<Telephone> it = studentInput.getTelephones().iterator(); it
				.hasNext();) {
			e = it.next();
			if (e.getNumber() == null || e.getNumber() == "") {
				it.remove();
			}
		}

	}

	public boolean removeFax() {
		return studentInput.remove(faxToRemove);
	}

	public boolean removeTelephone() {
		return studentInput.remove(telephoneToRemove);
	}

	public void reset(ActionEvent e) {
		postConstruct();

	}

	public void setEmailToRemove(Email emailToRemove) {
		this.emailToRemove = emailToRemove;
	}

	public void setEmailTypeOptions(List<SelectItem> emailTypeOptions) {
		this.emailTypeOptions = emailTypeOptions;
	}

	public void setFaxToRemove(Fax faxToRemove) {
		this.faxToRemove = faxToRemove;
	}

	public void setPhoneCountryOptions(List<SelectItem> phoneCountryOptions) {
		this.phoneCountryOptions = phoneCountryOptions;
	}

	public void setPhoneTypeOptions(List<SelectItem> phoneTypeOptions) {
		this.phoneTypeOptions = phoneTypeOptions;
	}

	public void setStateOptions(List<SelectItem> stateOptions) {
		this.stateOptions = stateOptions;
	}

	public void setStudentInput(Studente studentInput) {

		this.studentInput = studentInput;

		/*
		 * If this comes from a list of students and we want to edit him.
		 */
		if (getStudentInput().getId() != null
				&& getStudentInput().getId() != 0L) {

			studentService.prepare(studentInput);

		}

	}

	public void setStudentOutput(Studente studentOutput) {
		this.studentOutput = studentOutput;
	}

	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}

	public void setTelephoneToRemove(Telephone telephoneToRemove) {
		this.telephoneToRemove = telephoneToRemove;
	}

	public void setTest(int test) {
		this.test = test;
	}

	public String submit() {
		removeEmptyEmails();
		removeEmptyFaxes();
		removeEmptyTelephones();
		Object u = getLoggedUser();
		if (u != null & u instanceof User && studentInput.getAdder() == null)
			studentInput.setAdder((User) u);
		studentInput.setInsertionDate(Calendar.getInstance().getTime());
		studentService.save(studentInput);
		studentOutput = studentInput;
		studentInput = new Studente();
		return "inserisciStudenteSuccess?faces-redirect=true";
	}

}
